# coding:utf-8
from typing import Dict

from fastapi import Query

from app.models.system import SystemDept
from app.admin.schemas.system import DeptBase, DeptUpdate
from app.utils.array import ArrayUtil


class SystemDeptService:
    # 列表
    async def tree_list(self, query: Query):
        lists = await SystemDept.filter(query).all()
        menus = [await obj.to_dict(m2m=True) for obj in lists]
        # menus = [await obj.to_dict(m2m=True) for obj in pydantic.parse_obj_as(List[SystemMenuOutDB], lists)]
        return ArrayUtil.list_to_tree(menus, 'id', 'pid', 'children')

    async def get_id(self, user_id: int):
        result = await SystemDept.get_or_none(id=user_id)
        return result

    async def find(self, query: Query):
        result = await SystemDept.get_or_none(query)
        return result

    async def create(self, obj_in: DeptBase):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        if obj_dict['leader'] is None:
            obj_dict['leader'] = ""
        if obj_dict['mobile'] is None:
            obj_dict['mobile'] = ""
        if obj_dict['remark'] is None:
            obj_dict['remark'] = ""
        result = await SystemDept.create(**obj_dict)
        return result

    async def update(self, obj_in: DeptUpdate):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        if obj_dict['remark'] is None:
            obj_dict['remark'] = ""
        # 删除键
        item_id = obj_dict.pop('id')
        result = await SystemDept.filter(id=item_id).update(**obj_dict)
        return result

    async def remove(self, item_id: int):
        item = await SystemDept.filter(id=item_id).first()
        if item:
            item.is_deleted = True
            await item.save()
            return True
        else:
            return False
